package com.itheima.admin.contorller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.exception.MyException;
import com.itheima.common.result.JsonResult;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhengbinghua
 * @since 2023-03-02
 */
@RestController
@RequestMapping("/category")
@Api(tags = "菜品分类")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
/**
 * 增加菜品
 *
 * @return
 */
@PostMapping
@ApiOperation(value = "添加菜品分类")
public JsonResult addCategory(@RequestBody Category category){
    categoryService.save(category);
    return JsonResult.success("添加分类成功！");
}
/**
 * 修改菜品分类
 *
 * @return
 */
@PostMapping
@ApiOperation(value = "修改菜品分类")
 public JsonResult updateCategory(@RequestBody Category category){
    //判断菜品是否存在
    LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
  wrapper.eq(Category::getName, category.getName());
    Category category1 = categoryService.getOne(wrapper);
    if (null==category1){
        throw  new MyException(404, "菜品不存在");
    }
    //存在，修改数据
    LambdaUpdateWrapper<Category> updateWrapper = new LambdaUpdateWrapper<>();
    updateWrapper.eq(Category::getId,category.getId());
     categoryService.update(category, updateWrapper);
     return JsonResult.success("修改分类成功！");

}
/**
 * 删除分类
 *
 * @return
 */
@DeleteMapping()
@ApiOperation(value = "删除分类")
    public JsonResult deleteCategory(String id){
    categoryService.removeById(id);
    return JsonResult.success("删除成功！");
    }
    /**
     * 菜品分页查询
     *
     * @return
     */
@GetMapping("page")
@ApiOperation(value = "菜品分页显示")
    public JsonResult getCategoryByPage(@ApiParam(value = "当前页面") Integer page,
                                       @ApiParam(value = "每页显示条数") Integer pageSize){
    Page<Category> page1 = new Page<>(page, pageSize);
    Page<Category> categoryPage = categoryService.page(page1);
    return JsonResult.success(categoryPage);
}
   /**
    * 分类下拉
    *
    * @return
    */
   @GetMapping("list")
    @ApiOperation(value = "菜品下拉")
    public JsonResult getCategotyList(String type){
       LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
       wrapper.eq(Category::getType,type);
       //按排名降序排序
       wrapper.orderByDesc(Category::getSort);
       //保持网页数据最新
       wrapper.orderByDesc(Category::getUpdateTime);
       List<Category> categories = categoryService.list(wrapper);
    return JsonResult.success(categories);
   }
}
